package com.shuzhi.dataway.task;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.retry.backoff.FixedBackOffPolicy;
import org.springframework.retry.policy.SimpleRetryPolicy;
import org.springframework.retry.support.RetryTemplate;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Siyuan.mlq
 * @version 1.0
 * @description
 * @since 2021/1/14
 */
@Slf4j
@Component
public class RetryTask {

  @Autowired private RetryTaskHandler retryTaskHandler;

  /** 重试机制和执行调用 */
  public void doTask() {

    Map<Class<? extends Throwable>, Boolean> exceptionMap = new HashMap<>();

    // 构建重试模板实例
    RetryTemplate retryTemplate = new RetryTemplate();

    FixedBackOffPolicy fixedBackOffPolicy = new FixedBackOffPolicy();
    fixedBackOffPolicy.setBackOffPeriod(1000L);

    SimpleRetryPolicy simpleRetryPolicy = new SimpleRetryPolicy(3, exceptionMap);

    retryTemplate.setBackOffPolicy(fixedBackOffPolicy);
    retryTemplate.setRetryPolicy(simpleRetryPolicy);

    retryTemplate.execute(
        retryContext -> {
          Boolean result = retryTaskHandler.doTry();
          log.info("执行重试结束");
          return result;
        },
        retryContext -> {
          log.info("执行重试次数结束");
          return false;
        });
  }
}
